package top.drinyeit.nongmao.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.acker.simplezxing.activity.CaptureActivity;

import java.util.ArrayList;
import java.util.List;

import top.drinyeit.nongmao.R;
import top.drinyeit.nongmao.adapter.MainFragmentAdapter;
import top.drinyeit.nongmao.base.BaseActivity;
import top.drinyeit.nongmao.fragment.ClassificationFragment;
import top.drinyeit.nongmao.fragment.HomeFragment;
import top.drinyeit.nongmao.fragment.MineFragment;
import top.drinyeit.nongmao.fragment.ShopFragment;

public class MainActivity extends BaseActivity {
    private ViewPager main_viewPage;
    List<Fragment> list = new ArrayList<Fragment>();
    MainFragmentAdapter mainFragmentAdapter;
    public int position = 0;
    private long exitTime = 0;
    private LinearLayout home;//主页
    private LinearLayout classification;//分类
    private LinearLayout lanzi;//篮子
    private LinearLayout mine;//我的
    private TextView homeText, classificationText, cartText, mineText;
    public int topHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initIntent();
        main_viewPage = (ViewPager) findViewById(R.id.main_viewPage);

        //界面按钮
        home = (LinearLayout) findViewById(R.id.home);
        classification = (LinearLayout) findViewById(R.id.classification);
        lanzi = (LinearLayout) findViewById(R.id.lanzi);
        mine = (LinearLayout) findViewById(R.id.mine);
        homeText = findViewById(R.id.tv_home);
        classificationText = findViewById(R.id.tv_classification);
        cartText = findViewById(R.id.tv_cart);
        mineText = findViewById(R.id.tv_mine);

        list.add(new HomeFragment());
        list.add(new ClassificationFragment());
        list.add(new ShopFragment());
        list.add(new MineFragment());

        mainFragmentAdapter = new MainFragmentAdapter(getSupportFragmentManager(), list);
        main_viewPage.setAdapter(mainFragmentAdapter);
        main_viewPage.setOffscreenPageLimit(4);
        main_viewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        change(position);
        position = main_viewPage.getCurrentItem();
        init();
    }

    private void initIntent() {
        if (getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            position = bundle.getInt("position");
        }
    }

    @Override
    public void init() {
        //按钮点击切换fr
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                position = 0;
                change(position);
            }
        });

        classification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                position = 1;
                change(position);
            }
        });

        lanzi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                position = 2;
                change(position);
            }
        });

        mine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                position = 3;
                change(position);
            }
        });
    }


    //切换vp
    public void change(int position) {
        switch (position) {
            case 0:
                main_viewPage.setCurrentItem(0);
                home.setSelected(true);
                classification.setSelected(false);
                lanzi.setSelected(false);
                mine.setSelected(false);
                homeText.setTextColor(ContextCompat.getColor(this, R.color.app_green));
                classificationText.setTextColor(ContextCompat.getColor(this, R.color.warmGrey));
                cartText.setTextColor(ContextCompat.getColor(this, R.color.warmGrey));
                mineText.setTextColor(ContextCompat.getColor(this, R.color.warmGrey));
                this.position = 0;
                break;
            case 1:
                main_viewPage.setCurrentItem(1);
                home.setSelected(false);
                classification.setSelected(true);
                lanzi.setSelected(false);
                mine.setSelected(false);
                homeText.setTextColor(ContextCompat.getColor(this, R.color.warmGrey));
                classificationText.setTextColor(ContextCompat.getColor(this, R.color.app_green));
                cartText.setTextColor(ContextCompat.getColor(this, R.color.warmGrey));
                mineText.setTextColor(ContextCompat.getColor(this, R.color.warmGrey));
                this.position = 1;
                break;
            case 2:
                main_viewPage.setCurrentItem(2);
                home.setSelected(false);
                classification.setSelected(false);
                lanzi.setSelected(true);
                mine.setSelected(false);
                homeText.setTextColor(ContextCompat.getColor(this, R.color.warmGrey));
                classificationText.setTextColor(ContextCompat.getColor(this, R.color.warmGrey));
                cartText.setTextColor(ContextCompat.getColor(this, R.color.app_green));
                mineText.setTextColor(ContextCompat.getColor(this, R.color.warmGrey));
                this.position = 2;
                break;
            default:
                main_viewPage.setCurrentItem(3);
                home.setSelected(false);
                classification.setSelected(false);
                lanzi.setSelected(false);
                mine.setSelected(true);
                homeText.setTextColor(ContextCompat.getColor(this, R.color.warmGrey));
                classificationText.setTextColor(ContextCompat.getColor(this, R.color.warmGrey));
                cartText.setTextColor(ContextCompat.getColor(this, R.color.warmGrey));
                mineText.setTextColor(ContextCompat.getColor(this, R.color.app_green));
                this.position = 3;
                break;
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        Rect frame = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;//状态栏高度

        int titleBarHeight = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();//标题栏高度
        topHeight = titleBarHeight + statusBarHeight;
    }

    public class ReceiveBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().contains("show")) {
                change(1);
            }

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CaptureActivity.REQ_CODE:
                switch (resultCode) {
                    case RESULT_OK:
//                        tvResult.setText(data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));  //or do sth

                        if (data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT).length() == 11) {
                            Intent intent = new Intent();
                            intent.putExtra("type", "0");
                            intent.putExtra("phone", data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                            intent.setClass(MainActivity.this, SetupActivity.class);
                            startActivity(intent);
                        } else {
                            showToast("请扫描正确的推荐人二维码");
                        }

                        break;
                    case RESULT_CANCELED:
                        if (data != null) {
                            // for some reason camera is not working correctly
//                            tvResult.setText(data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                            showToast(data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                        }
                        break;
                }
                break;
        }
    }

    private boolean isQuit = false;

    @Override
    public void onBackPressed() {

        if (!isQuit) {
            Toast.makeText(MainActivity.this, "再按一次退出" + R.string.app_name, Toast.LENGTH_SHORT).show();
            isQuit = true;

            //两秒钟之后isQuit会变成false
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        isQuit = false;
                    }
                }
            }).start();


        } else {
            System.exit(0);
        }
    }

    //2次返回退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次返回键退出" + getString(R.string.app_name),
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    /**
     * @param intent
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            position = intent.getExtras().getInt("position");
        } else {
            position = 0;
        }
        change(position);
    }
}
